<template>
  <div class="forget">
    <nav-bar></nav-bar>
    <el-card>
      <h2 class="title">邮箱验证</h2>
      <el-form :model="forgetPassForm"
               status-icon
               :rules="rules"
               ref="forgetPassForm"
               label-width="70px"
               class="forgetPassForm">
        <el-form-item label="邮箱" prop="email">
          <el-input type="email"
                    placeholder="请输入邮箱"
                    v-model="forgetPassForm.email"
                    autocomplete="off"></el-input>
        </el-form-item>

        <div class="verify clearfix">
          <el-form-item label="验证码" prop="code">
            <el-input type="code"
                      placeholder="请输入验证码"
                      v-model="forgetPassForm.code"
                      autocomplete="off"></el-input>
            <el-button type="primary"
                       @click="verify"
                       :disabled="!canVerify">{{verifyTip}}</el-button>
          </el-form-item>
        </div>


        <el-form-item label="新的密码" prop="newPass">
          <el-input type="password"
                    placeholder="请输入新的密码"
                    v-model="forgetPassForm.newPass"
                    autocomplete="off"
                    show-password></el-input>
        </el-form-item>

        <el-form-item class="submit">
          <el-button type="primary" @click="submitForm('forgetPassForm')">修改</el-button>
          <el-button @click="resetForm('forgetPassForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

  </div>
</template>

<script>
  import NavBar from "components/content/navBar/NavBar";

  // 引入类和方法
  import {verify, resetPass} from "network/forgetPass";
  import {routerReplaceTimeout} from "common/Utils";

  export default {
    name: "ForgetPass",
    components: {
      NavBar
    },
    data() {
      let validateEmail = (rule, value, callback) => {
        if (value == "") {
          callback(new Error('邮箱不能为空'))
        }
        const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        if (!emailReg.test(value)) {
          callback(new Error('请输入正确的邮箱'))
        } else {
          callback()
        }
      };
      let validateCode = (rule, value, callback) => {
        if (value == "") {
          callback(new Error('验证码不能为空'))
        } else {
          callback()
        }
      };
      let validateNewPass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('密码不能为空'));
        }
        const passReg = /^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$/
        if(!passReg.test(value)) {
          callback(new Error('密码位数为6位以上并且需要包括字母（大小写）、数字、特殊符号'));
        } else {
          callback();
        }
      };
      return {
        forgetPassForm: {
          email: '',
          code: '',
          newPass: '',
        },
        verifyCode: '',
        canVerify: true,
        count: 180,
        rules: {
          email: [
            {validator: validateEmail, trigger: 'blur'}
          ],
          code: [
            {validator: validateCode, trigger: 'blur'}
          ],
          newPass: [
            {validator: validateNewPass, trigger: 'blur'}
          ]
        }

      }
    },
    computed: {
      verifyTip() {
        return this.canVerify? '免费发送验证码' : `${this.count}秒后可重新发送`
      }
    },
    methods: {
      verify() {
        if(this.forgetPassForm.email) {
          const verifyEmail = {
            email: this.forgetPassForm.email
          }
          verify(verifyEmail).then(res => {
            this.verifyCode = res.data.data.code
            this.countdown()
          })
        }else {
          this.$toast.show('请先输入邮箱，再发送验证码')
        }
      },
      countdown() {
        const time = 180
        this.canVerify = false
        let timer = setInterval(() => {
          if(time - this.count < 179) {
            this.count --
          }else {
            clearInterval(timer)
            this.count = 180
            this.canVerify = true
          }
        }, 1000)
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const resetMessage = {
              email: this.forgetPassForm.email,
              password: this.forgetPassForm.newPass
            }
            if(this.forgetPassForm.code === this.verifyCode) {
              resetPass(resetMessage).then(res => {
                console.log(res)
                if(res.data.code) {
                  this.$toast.show('密码修改成功，请重新登录', 'success', 1000)
                  routerReplaceTimeout(this.$router, '/login', 1000)
                }else {
                  this.$toast.show('账号不存在，请先完成注册', 1000)
                  routerReplaceTimeout(this.$router, '/register', 1000)
                }
              })
            }else {
              this.$toast.show('验证码错误', 'failure', 1000)
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  }
</script>

<style scoped>
  .forget {
    width: 500px;
    margin: 120px auto 0;
  }

  .title {
    padding-bottom: 20px;
    margin-bottom: 30px;
    border-bottom: 1px solid #eeeeee;
    text-align: center;
    font-size: 24px;
  }

  .el-card >>> .el-card__body {
    padding: 30px 40px 40px 30px;
  }

  .forgetPassForm >>> .verify .el-form-item .el-input {
    float: left;
    width: 150px;
  }

  .forgetPassForm >>> .verify .el-form-item .el-button {
    float: right;
    width: 200px;
    text-align: center;
  }

  .forgetPassForm >>> .el-button--primary {
    background-color: #4361a7;
    border-color: #4361a7;
    color: #fff;
  }

  .forgetPassForm >>> .el-button--primary:hover {
    background-color: #5177ce;
    border-color: #5177ce;
    color: #fff;
  }

  .submit .el-button--primary {
    margin-right: 10px;
  }

  p {
    margin: -5px 0 0 70px;
    font-size: 12px;
    color: #8F9395;
  }

  p span {
    color: #4361a7;
    cursor: pointer;
  }
</style>
